<?php
/**
 * +-------------------------------------------------------------
 * |Caption:
 * +-------------------------------------------------------------
 * |Author: Lenny
 * +-------------------------------------------------------------
 * |Email:  1685964109@qq.com
 * +-------------------------------------------------------------
 * |Date:   2024/6/18 下午2:22
 * +-------------------------------------------------------------
 */

namespace app\common\middleware;

use app\common\traits\JsonTrait;
use Closure;
use ReflectionClass;

class CheckLogin
{
    use JsonTrait;

    public function handle($request, Closure $next)
    {
        // 获取应用
        $appName = app('http')->getName();
        if (empty($appName)) return $next($request);
        // 获取控制器名
        $controller = $request->controller();
        if (empty($controller)) return $next($request);
        if (str_contains($controller, '.')) $controller = str_replace('.', '\\', $controller);
        $controllerClass = "app\\{$appName}\\controller\\{$controller}";
        // 类的反射对象
        $classObj = new ReflectionClass($controllerClass);
        // 类的默认属性
        $properties = $classObj->getDefaultProperties();
        // 判断是否忽略(如果类中设置了ignoreAuth属性为true，则忽略验证登录)
        $ignoreAuth = $properties['ignoreAuth'] ?? false;
        // 获取会话信息
        $userInfo = session($appName);
        if (!$ignoreAuth) {
            if (empty($userInfo)) {
                return $this->errLogin('请先登录');
            }
            // 判断是否登录过期
            $expireTime = $userInfo['expire_time'];
            if ($expireTime !== true && time() > strtotime($expireTime)) {
                session($appName, null);
                return $this->errLogin('登录已过期，请重新登录');
            }
        }
        $request->userInfo = $userInfo ?: [];

        return $next($request);
    }
}